package com.interview.javabasic.DataStructrue;/*
@李子宁
Happy,happy everyday!
冲鸭！
*/

public class HashTabDemo {
    public static void main(String[] args) {

    }
}

class Emp{
    public int id;
    public String name;
    public Emp next;
    public Emp(int id,String name){
        super();
        this.id = id;
        this.name = name;
    }
}

class EmpList{
    private Emp head;
    //添加雇员
    //加载链表的最后添加
    public void add(Emp emp){
        if (head == null){
            head = emp;
            return;
        }
        Emp tmp = head;
        while (true){
            if (tmp.next ==null){
                break;
            }
            tmp = tmp.next;
        }
        tmp.next = emp;
    }

    //遍历
    public void list(int no){
        if (head == null){
            System.out.println("当前"+no+"链表为空");
            return;
        }
        System.out.println("当前"+no+"链表的信息：");
        Emp cur = head;
        while (true){
            System.out.println("id= "+cur.id+"name= "+cur.name);
            if (cur.next==null){
                break;
            }
            cur = cur.next;
        }
        System.out.println();
    }

    //查找
    public Emp findById(int id){
        if (head==null){
            return null;
        }
        Emp cur = head;
        while (true){
            if (cur.id==id){
                break;
            }
            if (cur.next == null){
                cur = null;
                break;
            }
            cur = cur.next;
        }
        return cur;
    }
}

//写hash表
class HashTab{
    private EmpList[] empLists;
    private int size;
    public HashTab(int size){
        this.size = size;
        //初始化链表
        empLists = new EmpList[size];
    }

    //添加雇员
    public void add(Emp emp){
        //根据员工的id得到应该加入的链表
        int emplistNo = hashFun(emp.id);
        //emp 加入到对应的链表
        for (int i = 0; i < size; i++) {
            empLists[i] = new EmpList();
        }
        empLists[emplistNo].add(emp);
    }

    //遍历所有的链表
    public void list(){
        for (int i=0;i<size;i++){
            empLists[i].list(i+1);
        }
    }

    //查找
    public void findById(int id){
        int emplistNo = hashFun(id);
        Emp emp = empLists[emplistNo].findById(id);
        if (emp!=null){
            System.out.println("在第"+(emplistNo+1)+"找到雇员"+id);
        }else{
            System.out.println("没有找到");
        }

    }


    //编写散列函数
    public int hashFun(int id){
        return id % size;
    }
}